﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Infrastructure.Pub;
using Infrastructure.Tool;
using SqlSugar;
using WsdShop.Model;
using WsdShop.Service;
using WsdShop.Model.ViewModels;

namespace Admin
{
    public class AuthorizeFilterAttribute : ActionFilterAttribute
    {
        public string MenuRole { get; set;  }
        public string OperateRole { get; set; }

        public AuthorizeFilterAttribute(string _MenuRole = "", string _OperateRole = "")
        {
            this.MenuRole = _MenuRole;
            this.OperateRole = _OperateRole;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //登录验证
            //UserInfoService userservice = new UserInfoService();
            //var user = userservice.GetCacheUser();
            string uid = Generator.GetCookie(PubConst.CookieUserKey);
            if (!uid.IsNullOrEmpty())
            {

                string uniqueKey = string.Format(PubConst.CacheUserKey, uid);
                var user = CacheManager<CacheUserInfo>.GetInstance()[uniqueKey];

                if (user == null || user.Id <= 0)
                {
                    filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Found;
                    //return;
                }
                else
                {
                    if (!user.IsAdmin)
                    {
                        //判断菜单权限
                        if (!MenuRole.IsNullOrEmpty())
                        {
                            if (!user.UserRoles.Any(m => m.MenuRole == MenuRole))
                            {
                                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                            }
                            else
                            {
                                //判断操作权限
                                if (!OperateRole.IsNullOrEmpty())
                                {
                                    if (!user.UserRoles.FirstOrDefault(m => m.MenuRole == MenuRole).OperateRoles.Contains(OperateRole))
                                    {
                                        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed;
                                    }
                                }
                            }
                        }
                    }

                }
            }
            else
            {
                filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Found;
                //return;
            }

        }
    }
}